<?php

namespace app\admin\controller\user;

use app\admin\model\Admin;
use app\admin\model\UserAdminBMessage;
use app\admin\model\UserAdminMessage;
use app\api\model\UserFoodAttrModel;
use app\api\model\UserFoodModel;
use app\api\model\InfoTypeRecord;
use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Tree;
use think\Model;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if($this->level == 2) {

                $expertModel = new \app\admin\model\UserExpert();
                $user_ids = $expertModel->where(['admin_id' => $this->auth->id])->column('user_id');

                $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->where('user.id','in',$user_ids)
                    ->order($sort, $order)
                    ->paginate($limit);

            }elseif($this->level == 1){
                if (empty($this->user_ids)){
                    $user_ids = [];
                }else{
                    $user_ids = explode(',',$this->user_ids);
                }

                $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->where('user.id','in',$user_ids)
                    ->order($sort, $order)
                    ->paginate($limit);
            }else{
                $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }


            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function health($ids)
    {
        $input = input('get.type');
        if(!empty($input)){
            $model = new UserAdminMessage();
            $message = $model->get($ids);
            $user = $this->model->get($message['user_id']);
            $this->view->assign('user_info',$user);
            $this->view->assign('type',1);
            $this->view->assign('message_id',$message['topic_id']);
            $this->view->assign('admin_id',$this->auth->id);
            return $this->view->fetch();
        }else{
            $user = $this->model->get($ids);
            $user['gender'] =  $user['gender'] > 0 ? '男' : '女';
            $this->view->assign('user_info',$user);
            $this->view->assign('type',0);
            $this->view->assign('message_id',0);
            $this->view->assign('admin_id',$this->auth->id);
            return $this->view->fetch();
        }


    }

    /**
     * 日统计
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function day_countinfo($ids)
    {
        $user = $this->model->get($ids);
        $user['gender'] =  $user['gender'] > 0 ? '男' : '女';

        $this->view->assign('user_info',$user);
        $this->view->assign('admin_id',$this->auth->id);
        return $this->view->fetch();
    }
    public function week_countinfo($ids)
    {
        $user = $this->model->get($ids);
        $user['gender'] =  $user['gender'] > 0 ? '男' : '女';

        $this->view->assign('user_info',$user);
        $this->view->assign('admin_id',$this->auth->id);
        return $this->view->fetch();
    }
	
	public function compare($ids)
	{
        $user = $this->model->get($ids);
        $user['gender'] =  $user['gender'] > 0 ? '男' : '女';
        $this->view->assign('user_info',$user);
        $this->view->assign('admin_id',$this->auth->id);
        return $this->view->fetch();
	}

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /*
     * 专家列表
     */
    public function expert()
    {

        if ($this->request->isPost()) {
            $input = input('post.');

            if(empty($input['endtime'])){
                $this->error('请选择最迟完成时间');
            }

            if(!empty($input['admin_id']) && !empty($input['user_id'])){

                $expertModel = new UserAdminMessage();

                $data = [
                    'zhuan_id'=>$input['admin_id'],
                    'endtime'=>strtotime($input['endtime'])
                ];

                $expertModel->where(['id'=>$input['user_id']])->update($data);

                $this->success('提交成功');

            }

        }
        $id = input('ids');

        $adminList = Admin::all(['level'=>2]);

        $this->view->assign('list',$adminList);

        $this->view->assign('user_id',$id);

        return $this->view->fetch();

    }


    /*
 * 专家列表
 */
    public function expert2()
    {

        if ($this->request->isPost()) {
            $input = input('post.');

            if(empty($input['endtime'])){
                $this->error('请选择最迟完成时间');
            }

            if(!empty($input['admin_id']) && !empty($input['user_id'])){

                $expertModel = new UserAdminBMessage();

                $data = [
                    'zhuan_id'=>$input['admin_id'],
                    'endtime'=>strtotime($input['endtime'])
                ];

                $expertModel->where(['id'=>$input['user_id']])->update($data);

                $this->success('提交成功');

            }

        }
        $id = input('ids');

        $adminList = Admin::all(['level'=>2]);

        $this->view->assign('list',$adminList);

        $this->view->assign('user_id',$id);

        return $this->view->fetch();

    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }


    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");

        if($this->level == 1) {
            if (empty($this->user_ids)) {
                $user_ids = [];
            } else {
                $user_ids = explode(',', $this->user_ids);
            }
            $custom['id'] = ['in',$user_ids];
        }

        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

}
